<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { getStudentScoreList, StudentScoreVO, downloadStudentScoreTemplate, exportStudentScore } from '@/api/excelFile/index';
import { MessagePlugin } from 'tdesign-vue-next';
import axios from 'axios';
import { ref as vueRef } from 'vue';
// 不再单独用downloadStudentScoreTemplate，直接用通用download

// 静态选项
const CLASS_OPTIONS = [
  { label: '全部', value: undefined },
  { label: '高三(1)班', value: '高三(1)班' },
  { label: '高三(2)班', value: '高三(2)班' },
  { label: '高三(3)班', value: '高三(3)班' },
];
const GENDER_OPTIONS = [
  { label: '全部', value: undefined },
  { label: '男', value: '男' },
  { label: '女', value: '女' },
];

// 查询参数
const searchForm = ref({
  className: undefined as string | undefined,
  gender: undefined as string | undefined,
});

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showPageSize: true,
});

// 表格数据
const tableData = ref<StudentScoreVO[]>([]);

// 多级表头配置
const headerConfig = ref([
  {
    colKey: 'class-title',
    title: computed(() => `${searchForm.value.className || '全部班级'}学生考勤和成绩`),
    align: 'center',
    children: [
      {
        colKey: 'col-group-1',
        title: '基础信息',
        align: 'center',
        children: [
          { colKey: 'name', title: '姓名', width: 100, align: 'center' },
          { colKey: 'age', title: '年龄', width: 80, align: 'center' },
          { colKey: 'gender', title: '性别', width: 80, align: 'center' }
        ]
      },
      {
        colKey: 'col-group-3',
        title: '学科成绩',
        align: 'center',
        colSpan: 9,
        children: [
          {
            colKey: 'col-group-3-0',
            title: '统考科目',
            align: 'center',
            children: [
              { colKey: 'chinese', title: '语文', width: 100, align: 'center' },
              { colKey: 'math', title: '数学', width: 100, align: 'center' },
              { colKey: 'english', title: '英语', width: 100, align: 'center' }
            ]
          },
          {
            colKey: 'col-group-3-1',
            title: '文科',
            align: 'center',
            children: [
              { colKey: 'politics', title: '政治', width: 100, align: 'center' },
              { colKey: 'history', title: '历史', width: 100, align: 'center' },
              { colKey: 'geography', title: '地理', width: 100, align: 'center' }
            ]
          },
          {
            colKey: 'col-group-3-2',
            title: '理科',
            align: 'center',
            children: [
              { colKey: 'physics', title: '物理', width: 100, align: 'center' },
              { colKey: 'biology', title: '生物', width: 100, align: 'center' },
              { colKey: 'chemistry', title: '化学', width: 100, align: 'center' }
            ]
          }
        ]
      },
      {
        colKey: 'col-group-4',
        title: '综合评价',
        align: 'center',
        children: [
          { colKey: 'attendance', title: '出勤', width: 100, align: 'center' },
          { colKey: 'performance', title: '表现', width: 100, align: 'center' }
        ]
      }
    ]
  }
]);

// 分页查询接口调用
const onQuery = () => {
  const params = {
    pageNum: pagination.value.current,
    pageSize: pagination.value.pageSize,
    className: searchForm.value.className,
    gender: searchForm.value.gender
  };

  console.log('[分页查询接口参数]', params);

  getStudentScoreList(params)
    .then((res) => {
      console.log('[分页查询接口响应结果]', res);
      if (res.data) {
        tableData.value = res.data.list;
        pagination.value.total = res.data.total || 0;
      } else {
        MessagePlugin.error('响应数据格式不正确');
      }
    })
    .catch((error) => {
      console.error('获取数据失败:', error);
      MessagePlugin.error('获取数据失败，请检查网络或联系管理员');
    });
};

// 重置查询条件
const onReset = () => {
  searchForm.value = { className: undefined, gender: undefined };
  pagination.value.current = 1;
  onQuery();
};

// 原生input导入实现
const fileInput = vueRef<HTMLInputElement | null>(null);
const triggerFileInput = () => {
  fileInput.value && fileInput.value.click();
};
const onFileChange = async (e: Event) => {
  const input = e.target as HTMLInputElement;
  const file = input.files && input.files[0];
  if (!file) return;
  const formData = new FormData();
  formData.append('file', file);
  try {
    const res = await axios.post(
      'http://localhost:9090/myAdminSystem/studentScore/import',
      formData,
      { headers: { 'Content-Type': 'multipart/form-data' } }
    );
    if (res.data && res.data.code === 200) {
      MessagePlugin.success(res.data.message || '导入成功');
      onQuery();
    } else {
      MessagePlugin.error(res.data?.message || '导入失败');
    }
  } catch (e) {
    MessagePlugin.error('导入异常');
  }
  // 清空 input，防止同一文件无法重复上传
  input.value = '';
};

// 导出处理
const handleExport = async () => {
  try {
    const params = {
      pageNum: pagination.value.current,
      pageSize: pagination.value.pageSize,
      className: searchForm.value.className,
      gender: searchForm.value.gender
    };
    const res = await exportStudentScore(params);
    const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = '学生成绩表.xlsx';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    MessagePlugin.success('导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    MessagePlugin.error('导出失败，请重试');
  }
};

// 下载模板
const handleDownloadTemplate = async () => {
  try {
    const res = await downloadStudentScoreTemplate();
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = '学生成绩导入模板.xlsx';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  } catch (error) {
    MessagePlugin.error('模板下载失败，请重试');
  }
};

// 分页变化时触发查询
const handlePageChange = (page: number) => {
  pagination.value.current = page;
  onQuery();
};

// 每页数量变化时触发查询
const handlePageSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.current = 1;
  onQuery();
};

onMounted(() => {
  onQuery();
});
</script>

<template>
  <div class="excel-container">
    <div class="search-form">
      <t-form layout="inline" :data="searchForm" label-width="auto">
        <t-form-item label="班级" name="className">
          <t-select v-model="searchForm.className" :options="CLASS_OPTIONS" placeholder="请选择班级" clearable style="width: 160px;" />
        </t-form-item>
        <t-form-item label="性别" name="gender">
          <t-select v-model="searchForm.gender" :options="GENDER_OPTIONS" placeholder="请选择性别" clearable style="width: 120px;" />
        </t-form-item>
        <t-form-item>
          <t-button theme="primary" @click="onQuery">查询</t-button>
          <t-button style="margin-left: 8px;" @click="onReset">重置</t-button>
          <input
            ref="fileInput"
            type="file"
            accept=".xlsx,.xls"
            style="display: none"
            @change="onFileChange"
          />
          <t-button style="margin-left: 8px;" @click="triggerFileInput">导入</t-button>
          <t-button style="margin-left: 8px;" @click="handleExport">导出</t-button>
          <t-button style="margin-left: 8px;" @click="handleDownloadTemplate">下载模板</t-button>
        </t-form-item>
      </t-form>
    </div>
    <t-table
      :data="tableData"
      :columns="headerConfig"
      row-key="name"
      bordered
      table-layout="auto"
      style="width: 100%"
    />
    <t-pagination
      v-model:current="pagination.current"
      v-model:page-size="pagination.pageSize"
      :total="pagination.total"
      :show-sizer="true"
      :layout="['total', 'prev', 'current', 'next', 'sizer']"
      style="margin-top: 16px; justify-content: flex-end;"
      @change="onQuery"
      @page-size-change="onQuery"
    />
  </div>
</template>

<style scoped lang="less">
.excel-container {
  padding: 20px;
}
.search-form {
  margin-bottom: 16px;
}
.header-group-row {
  background-color: #f5f7fa !important;
  font-weight: bold;
  font-size: 16px;
}
</style>
